//
//  JNTAddressBookViewController.m
//  OA
//
//  Created by 王文晓 on 16/8/4.
//  Copyright © 2016年 王文晓. All rights reserved.
//

#import "JNTAddressBookViewController.h"
#import "UserListTableViewCell.h"
#import "UserInfoModel.h"
#import "AddressSelectedToolsView.h"
#import "JNTDataRequestTools.h"
#import "JNTSearchTableViewController.h"

@interface JNTAddressBookViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,AddressSeletedToolsViewDeleagte>

@property (nonatomic, strong) NSMutableArray *sectionKeysArray;         //存放所有分区排序后的标题
@property (nonatomic, strong) NSMutableArray *rowArray;
@property (nonatomic, strong) NSMutableDictionary *allModelDic;     //存放model类的联系人
@property (nonatomic, strong) NSMutableDictionary *allDataDic;      //存放所有分区联系人

@property (nonatomic, strong) UITextField *textFiled;
@property (nonatomic, strong) NSMutableArray *searcherList;
@property (nonatomic, strong) AddressSelectedToolsView *selectedTools;

@end

@implementation JNTAddressBookViewController

- (void)viewDidLoad {
    [super viewDidLoad];

     UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard:)];
    [self.view addGestureRecognizer:tap];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.selectedTools];
 
    //block传值segementControll的回调
//    self.selectedTools.selectedPageBlock = ^(NSInteger i) {
//        
//        
//    };
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self makeData];
    [self.tableView reloadData];
}

//轻拍手势回收键盘
- (void)hideKeyboard:(UITapGestureRecognizer *)sender{
    
//    self.textFiled.text = nil;
    [self.view endEditing:YES];
    
}

#pragma mark - --------tableView的代理方法-------
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {

    
    return self.sectionKeysArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSString *key = [self.sectionKeysArray objectAtIndex:section];
    NSArray *array = [self.allModelDic objectForKey:key];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UserListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserListCell" forIndexPath:indexPath];
    
    NSString *key = [self.sectionKeysArray objectAtIndex:indexPath.section];
    NSArray *array = [self.allModelDic objectForKey:key];
    UserInfoModel *model = [array objectAtIndex:indexPath.row];
    cell.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.05];
    [cell setCellWithModel:model];
    NSLog(@"model = %@",model.name);
    return cell;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width-30, 30)];
    view.backgroundColor = [UIColor colorWithRed:arc4random()%255/256.0 green:arc4random()%255/256.0 blue:arc4random()%255/256.0 alpha:1.0];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 20, view.frame.size.height-5)];
    label.text = [self.sectionKeysArray objectAtIndex:section];
    [view addSubview:label];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 30;
}

//右边索引
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return [self sectionKeysArray];
}


#pragma mark - -------数据-------
- (void)makeData {
    
    NSDictionary *person_1=[[NSDictionary alloc]initWithObjectsAndKeys:@"s石峰",@"name",@"183-9247-5589",@"phone", nil];
    NSDictionary *person_2=[[NSDictionary alloc]initWithObjectsAndKeys:@"w王文晓",@"name",@"136-0925-7600",@"phone",nil];
    NSDictionary *person_3=[[NSDictionary alloc]initWithObjectsAndKeys:@"s孙飞燕",@"name",@"157-7196-8142",@"phone", nil];
    NSDictionary *person_4=[[NSDictionary alloc]initWithObjectsAndKeys:@"w王云龙",@"name",@"186-0297-5589",@"phone",nil];
    NSDictionary *person_5=[[NSDictionary alloc]initWithObjectsAndKeys:@"c程洁",@"name",@"157-6923-9092",@"phone",nil];
    NSDictionary *person_6=[[NSDictionary alloc]initWithObjectsAndKeys:@"z朱鹏",@"name",@"152-9198-5350",@"phone", nil];
    NSDictionary *person_7=[[NSDictionary alloc]initWithObjectsAndKeys:@"w王浩",@"name",@"132-9912-5710",@"phone", nil];
    NSDictionary *person_12=[[NSDictionary alloc]initWithObjectsAndKeys:@"l李帅",@"name",@"138-5438-5438",@"phone", nil];
    NSDictionary *person_13=[[NSDictionary alloc]initWithObjectsAndKeys:@"g郭亮",@"name",@"177-9132-2106",@"phone", nil];
    NSDictionary *person_14=[[NSDictionary alloc]initWithObjectsAndKeys:@"m毛邵谦",@"name",@"182-2083-9930",@"phone", nil];
    NSDictionary *person_15=[[NSDictionary alloc]initWithObjectsAndKeys:@"l廖辉",@"name",@"132-5990-7625",@"phone",nil];
    NSDictionary *person_16=[[NSDictionary alloc]initWithObjectsAndKeys:@"l老王",@"name",@"134-8447-4409",@"phone", nil];
    NSDictionary *person_17=[[NSDictionary alloc]initWithObjectsAndKeys:@"r若晨",@"name",@"187-1048-4221",@"phone", nil];
    NSDictionary *person_18=[[NSDictionary alloc]initWithObjectsAndKeys:@"w王永旭",@"name",@"177-9325-0206",@"phone", nil];
    NSDictionary *person_19=[[NSDictionary alloc]initWithObjectsAndKeys:@"c陈荣昌",@"name",@"182-2056-3715",@"phone", nil];
    NSDictionary *person_20=[[NSDictionary alloc]initWithObjectsAndKeys:@"w王勇",@"name",@"159-9175-7067",@"phone", nil];

    NSMutableArray *mArray = [NSMutableArray arrayWithObjects:person_1,person_2,person_3,person_4,person_5,person_6,person_7,person_12,person_13,person_14,person_15,person_16,person_17,person_18,person_19,person_20, nil];
//    mArray = @[];
    //将所有人按分区加载
    for (int i = 0; i < mArray.count; i++) {
        
        //先从临时数组中将字典取出
        NSDictionary *userInfoDic = [mArray objectAtIndex:i];
        //取出联系人姓名
        NSString *nameStr = [userInfoDic objectForKey:@"name"];
        NSString *upFirstStr = [self transformCharacter:nameStr];
        NSMutableArray *array = [self.allDataDic objectForKey:upFirstStr];
        if (array) {
            
            [array addObject:userInfoDic];
        }else {
            
            array = [[NSMutableArray alloc] initWithObjects:userInfoDic, nil];
            [self.allDataDic setObject:array forKey:upFirstStr];
        }
    }
    //排序
    [self sortAllKeys:self.allDataDic.allKeys];
    //model存储
    [self dicTransformToModelWithDic:self.allDataDic];
    
}


//汉字转拼音，截取首字母并大写
- (NSString *)transformCharacter:(NSString *)sourceStr {
    
    NSMutableString *ms = [NSMutableString stringWithString:sourceStr];
    if (!ms.length == 0) {
        
        //将汉字转换为拼音
        CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformToLatin, NO);
        //将拼音的声调去掉
        CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformStripDiacritics, NO);
        //将字符串所有的字母大写
        NSString *upStr = [ms uppercaseString];
        //首字母截取
        NSString *firstStr = [upStr substringToIndex:1];
        return firstStr;
    }
    return @"#";
}

//排序
- (void)sortAllKeys : (NSArray *)array{
    
    self.sectionKeysArray = [[NSMutableArray alloc] initWithArray:array];
    for (int i = 0; i < self.sectionKeysArray.count; i++) {
        
        for (int j = 0; j < self.sectionKeysArray.count - i - 1; j++) {
            
            if ([self.sectionKeysArray[j] compare:self.sectionKeysArray[j+1]] > 0) {
                
                [self.sectionKeysArray exchangeObjectAtIndex:j withObjectAtIndex:j+1];
            }
        }
    }
}

//转换为model
- (void)dicTransformToModelWithDic:(NSDictionary *)dic {
    
    for (NSString *key in _sectionKeysArray) {
        
        NSMutableArray *sectionArray = [[NSMutableArray alloc] init];
        NSArray *smallArray = [self.allDataDic objectForKey:key];
        for (int i = 0; i < smallArray.count; i++) {
            
            NSDictionary *userInfoDic = [smallArray objectAtIndex:i];
            UserInfoModel *userInfoM = [[UserInfoModel alloc] init];
            [userInfoM setValuesForKeysWithDictionary:userInfoDic];
            [sectionArray addObject:userInfoM];
        }
        [self.allModelDic setObject:sectionArray forKey:key];
    }
}

#pragma mark - -------搜索框-------
- (UIView *)setSearchView {
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width-100, 40)];
    
    self.textFiled = [[UITextField alloc] initWithFrame:CGRectMake(20, 0, view.frame.size.width-40, 25)];
    self.textFiled.placeholder = @"姓名、工号、电话、手机";
    [view addSubview:self.textFiled];
    self.textFiled.delegate =self;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, view.frame.size.height-10, view.frame.size.width-80, 1)];
    label.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    [view addSubview:label];
    
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, view.frame.size.height-1, self.view.frame.size.width, 1)];
    lineLabel.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.3];
    [view addSubview:lineLabel];
    
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(view.frame.size.width-50, 0, 40, 40)];
    [btn addTarget:self action:@selector(searchBtn:) forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:[UIImage imageNamed:@"title_btn_search_s.png"] forState:UIControlStateNormal];
    [view addSubview:btn];
 
    return view;
}

#pragma mark --请求数据--
- (void)fenchDataSourceWithUrlString:(NSString *)urlStr parameter:(NSMutableDictionary *)parameter {
    
    
    [JNTDataRequestTools postFetchDataWithUrlString:urlStr paramenters:parameter success:^(id data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        NSLog(@"我的订单-----%@", [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        NSMutableArray *array = dic[@"items"];
        for (int i = 0; i < array.count; i++) {
            
            //先从临时数组中将字典取出
            NSDictionary *userInfoDic = [array objectAtIndex:i];
            //取出联系人姓名
            NSString *nameStr = [userInfoDic objectForKey:@"name"];
            NSString *upFirstStr = [self transformCharacter:nameStr];
            NSMutableArray *array = [self.allDataDic objectForKey:upFirstStr];
            if (array) {
                
                [array addObject:userInfoDic];
            }else {
                
                array = [[NSMutableArray alloc] initWithObjects:userInfoDic, nil];
                [self.allDataDic setObject:array forKey:upFirstStr];
            }
        }
        //排序
        [self sortAllKeys:self.allDataDic.allKeys];
        //model存储
        [self dicTransformToModelWithDic:self.allDataDic];
        

//        
        [self.tableView reloadData];
    } fail:^{
        
        NSLog(@"通讯录请求失败");
    } view:self.tableView];
    
}

//搜索按钮回调
- (void)searchBtn:(UIButton *)sender {
    NSLog(@"sdfsdgdfgfd");
    if (self.textFiled.text.length != 0) {
        
        NSString *url = @"http://111.206.82.216:8050/JBaas/user/findByName?authCode=APP*JNT@2015E0298TR";
        NSMutableDictionary *mdic = [NSMutableDictionary dictionaryWithObjectsAndKeys:self.textFiled.text,@"name",nil];
        [self.allModelDic removeAllObjects];
        [self.sectionKeysArray removeAllObjects];
        [self.tableView reloadData];
        [self fenchDataSourceWithUrlString:url parameter:mdic];
//        JNTSearchTableViewController *searchVC = [[JNTSearchTableViewController alloc] init];
//        searchVC.searchStr = self.textFiled.text;
//        [self.navigationController pushViewController:searchVC animated:NO];
        
    }else {
        
        
    }
    [self.tableView reloadData];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - -------laying-------
- (UITableView *)tableView {
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 90, self.view.frame.size.width, self.view.frame.size.height)];
        [_tableView registerNib:[UINib nibWithNibName:@"UserListTableViewCell" bundle:nil] forCellReuseIdentifier:@"UserListCell"];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (NSMutableArray *)sectionKeysArray {
    
    if (!_sectionKeysArray) {
        
        _sectionKeysArray = [[NSMutableArray alloc] init];
    }
    return _sectionKeysArray;
}

- (NSMutableDictionary *) allModelDic {
    
    if (!_allModelDic) {
        
        _allModelDic = [[NSMutableDictionary alloc] init];
    }
    return _allModelDic;
}

- (NSMutableDictionary *)allDataDic {
    
    if (!_allDataDic) {
        
        _allDataDic = [[NSMutableDictionary alloc]init];
    }
    return _allDataDic;
}

- (AddressSelectedToolsView*)selectedTools {
    
    if (!_selectedTools) {
        
        NSArray *ar = @[@"集团公司",@"股份公司",@"股份公司",@"智慧城市工程研究所"];
        _selectedTools = [[AddressSelectedToolsView alloc] initLHSelectedNavigationViewToolsWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 80) ButtonTitle:ar searchView:[self setSearchView]];
        _selectedTools.delegate = self;
    }
    return _selectedTools;
}


- (void)buttonAction:(id)but {
    
    [self makeData];
    [self.tableView reloadData];
}


@end
